<template>
  <div class="container">
    <div class="app-container">
      <div class="left">
        <el-input
          v-model="queryParams.keyword"
          style="margin-bottom: 10px"
          type="text"
          prefix-icon="el-icon-search"
          size="small"
          placeholder="输入员工姓名全员搜索"
          @input="inputChange"
        />
        <!-- 树形组件 -->
        <el-tree
          ref="treeDept"
          :data="depts"
          :props="defaultProps"
          node-key="id"
          :default-checked-keys="[1]"
          default-expand-all
          :expand-on-click-node="false"
          highlight-current
          @current-change="selectedNode"
        />
      </div>
      <div class="right">
        <el-row class="opeate-tools" type="flex" justify="end">
          <el-button size="mini" type="primary" @click="$router.push({name:'DetailPage'})">添加员工</el-button>
          <el-button size="mini" @click="showExcelDialog=true">excel导入</el-button>
          <el-button size="mini" @click="exportExcel">excel导出</el-button>
        </el-row>
        <!-- 表格组件 -->
        <el-table :data="employeeList">
          <el-table-column prop="staffPhoto" align="center" label="头像">
            <template #default="{ row }">
              <el-avatar
                v-if="row.staffPhoto"
                :src="row.staffPhoto"
                :size="30"
              />
              <span v-else class="username">{{ row.username?.charAt(0) }}</span>
            </template>
          </el-table-column>
          <el-table-column prop="username" label="姓名" />
          <el-table-column prop="mobile" label="手机号" sortable />
          <el-table-column prop="workNumber" label="工号" sortable />
          <el-table-column prop="formOfEmployment" label="聘用形式">
            <template #default="{ row }">
              <span v-if="row.formOfEmployment === 1">正式</span>
              <span v-else-if="row.formOfEmployment === 2">非正式</span>
            </template>
          </el-table-column>
          <el-table-column prop="departmentName" label="部门" />
          <el-table-column prop="timeOfEntry" label="入职时间" sortable />
          <el-table-column label="操作" width="280px">
            <template #default="{row}">
              <el-button size="mini" type="text" @click="$router.push({name:'DetailPage',params:{id:row.id}})">查看</el-button>
              <el-button size="mini" type="text" @click="btnRole(row.id)">角色</el-button>
              <el-button size="mini" type="text" @click="delEmployee(row.id)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>

        <!-- 分页 -->
        <el-row style="height: 60px" align="middle" type="flex" justify="end">
          <el-pagination
            :current-page="queryParams.page"
            :page-size="queryParams.pagesize"
            layout="total,prev, pager, next"
            :total="total"
            @current-change="currentChange"
          />
        </el-row>
        <!-- 分页 -->
      </div>
    </div>
    <ImportExcel :show-excel-dialog.sync="showExcelDialog" @updateEmployee="getEmployeeList" />
    <el-dialog :visible.sync="showRoleDialog" title="分配角色">
      <!-- 弹层内容 -->
      <!-- checkbox -->
      <el-checkbox-group v-model="roleIds">
        <!-- 放置n个的checkbox  要执行checkbox的存储值 item.id-->
        <el-checkbox
          v-for="item in roleList"
          :key="item.id"
          :label="item.id"
        >{{ item.name }}</el-checkbox>
      </el-checkbox-group>
      <el-row slot="footer" type="flex" justify="center">
        <el-col :span="6">
          <el-button type="primary" size="mini" @click="assignRole">确定</el-button>
          <el-button size="mini">取消</el-button>
        </el-col>
      </el-row>
    </el-dialog>
  </div>
</template>

<script>
import { getEmployeeList, exportEmployee, delEmployee, getEnableRoleList, getEmployeeDetail, assignRole } from '@/api/employee'
import { getDepartment } from '@/api/department'
// import _ from 'lodash'
import FileSaver from 'file-saver'
import ImportExcel from './components/import-excel.vue'
export default {
  name: 'Employee',
  components: { ImportExcel },
  data() {
    return {
      employeeId: '',
      checkList: '',
      showRoleDialog: false, // 用来控制角色弹层的显示
      roleList: [], // 接收角色列表
      roleIds: [], // 用来双向绑定数据的

      showExcelDialog: false, // 控制excel的弹层显示和隐藏
      depts: [], // 组织数据
      employeeList: [], // 员工数据列表
      defaultProps: {
        label: 'name',
        children: 'children'
      },
      // queryParams对象是将来需要用来做查询的参数数据
      queryParams: {
        page: 1,
        pagesize: 10,
        keyword: null,
        // departmentId记录 当前选中的部门的编号
        departmentId: null
      },
      total: 0,
      timeId: null
    }
  },
  async created() {
    await this.getDepartment()
    await this.getEmployeeList()
  },
  methods: {
    async assignRole() {
      await assignRole({
        id: this.employeeId,
        roleIds: this.roleIds
      })
      this.showRoleDialog = false
      this.$message.success('分配角色成功')
    },
    async btnRole(id) {
      this.roleIds = []
      const res = await getEnableRoleList()
      this.roleList = res
      const list = await getEmployeeDetail(id)
      this.roleIds = list.roleIds
      this.showRoleDialog = true
      this.employeeId = id
    },
    async delEmployee(id) {
      await delEmployee(id)
      this.$message.success('员工删除成功')
      console.log(this.employeeList)
      if (this.employeeList.length === 1) {
        this.queryParams.page--
      }
      this.getEmployeeList()
    },
    async exportExcel() {
      const res = await exportEmployee()
      console.log(res)
      FileSaver.saveAs(res, '员工信息表.xlsx')
    },
    inputChange() {
      clearTimeout(this.timeId)
      this.timeId = setTimeout(() => {
        this.queryParams.page = 1
        this.getEmployeeList(this.queryParams)
      }, 500)
    },
    currentChange(current) {
      this.queryParams.page = current
      this.getEmployeeList()
    },
    async getEmployeeList() {
      const res = await getEmployeeList(this.queryParams)
      // console.log(res, '12312312312312312')
      this.employeeList = res.rows
      this.total = res.total
    },
    selectedNode(val) {
      this.queryParams.departmentId = val.id
      this.queryParams.page = 1
      this.getEmployeeList()
    },
    async getDepartment() {
      const res = await getDepartment()
      // console.log(res)

      // 声明一个找儿子的函数
      function getChildren(id) {
        return res.filter((v) => v.pid === id)
      }
      //
      res.forEach((v) => {
        v.children = getChildren(v.id)
      })

      // 将一级节点找出来
      const list = res.filter((v) => v.pid === 0)
      // console.log(list, 'list')
      this.depts = list

      // 设置比默认的部门id
      this.queryParams.departmentId = this.depts[0].id
      // 等到树状解构加载渲染完毕之后，再设置默认选中项目
      this.$nextTick(() => {
        // 设置默认选中项目
        this.$refs.treeDept.setCurrentKey(this.queryParams.departmentId)
      })
    }
  }
}
</script>

<style lang="scss" scoped>
.app-container {
  background: #fff;
  display: flex;
  .left {
    width: 280px;
    padding: 20px;
    border-right: 1px solid #eaeef4;
  }
  .right {
    flex: 1;
    padding: 20px;
    .opeate-tools {
      margin: 10px;
    }
    .username {
      height: 30px;
      width: 30px;
      line-height: 30px;
      text-align: center;
      border-radius: 50%;
      color: #fff;
      background: #04c9be;
      font-size: 12px;
      display: inline-block;
    }
  }
}
::v-deep
  .el-tree--highlight-current
  .el-tree-node.is-current
  > .el-tree-node__content {
  color: skyblue;
}
</style>
